package com.example.demo.util;

import com.example.demo.constant.LockType;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Component
public class RedissonUtil {

    // RedissonClient已经由配置类生成，这里自动装配即可
    @Resource
    private RedissonClient redissonClient;

    /**
     * 锁住不设置超时时间(拿不到lock就不罢休，不然线程就一直block)
     *
     * @param lockKey
     * @return org.redisson.api.RLock
     */
    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    /**
     * leaseTime为加锁时间，单位为秒
     *
     * @param lockKey
     * @param leaseTime
     * @return org.redisson.api.RLock
     */
    public RLock lock(String lockKey, long leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(leaseTime, TimeUnit.SECONDS);
        return null;
    }

    /**
     * timeout为加锁时间，时间单位由unit确定
     *
     * @param lockKey
     * @param unit
     * @param timeout
     * @return org.redisson.api.RLock
     */
    public RLock lock(String lockKey, TimeUnit unit, long timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }

    /**
     * 尝试获取锁
     *
     * @param lockType  锁的类型
     * @param lockKey   锁的key
     * @param unit      锁的单位
     * @param waitTime  获取锁等待时间
     * @param leaseTime 锁自动释放时间
     * @return boolean
     */
    public boolean tryLock(LockType lockType, String lockKey, TimeUnit unit, long waitTime, long leaseTime) {
        RLock lock = null;
        switch (lockType) {
            case REENTRANT_LOCK:
                lock = redissonClient.getLock(lockKey);
                break;
            case FAIR_LOCK:
                lock = redissonClient.getFairLock(lockKey);
                break;
            case READ_LOCK:
                lock = redissonClient.getReadWriteLock(lockKey).readLock();
                break;
            case WRITE_LOCK:
                lock = redissonClient.getReadWriteLock(lockKey).writeLock();
                break;
            default:
                throw new RuntimeException("do not support lock type：" + lockType);
        }
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 通过lockKey解锁
     *
     * @param lockKey
     * @return void
     */
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    /**
     * 直接通过锁解锁
     *
     * @param lock
     * @return void
     */
    public void unlock(RLock lock) {
        lock.unlock();
    }
}
